package com.hx.util.encode;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public class EncodeUtil {

	private static String byte2Hex(byte b){
		int value = (b & 0x7F) + (b<0 ?0x80:0);
		return (value < 0x10 ? "0" : "") + Integer.toHexString(value).toLowerCase();
	}
	
	/**
	 * 
	 * MD5加密，提供原始字符进行加密码，此加密无解密机制；
	 * 
	 * @param pswd
	 * @return
	 */
	public static String MD5_32(String pswd){
		try {
			MessageDigest md5 = MessageDigest.getInstance("MD5");
			StringBuffer strbuf = new StringBuffer();
			
			md5.update(pswd.getBytes(),0,pswd.length());
			byte[] digest = md5.digest();
			
			for(int i=0;i<digest.length;i++){
				strbuf.append(byte2Hex(digest[i]));
			}
			
			return strbuf.toString();
		} catch (NoSuchAlgorithmException e) {
			throw new RuntimeException(e);
		}
	}
	/*
     * 页面转码
     */
	 public static String encode(String str,String encode){
	    	String s = null;
	    	try {
	    		s = java.net.URLEncoder.encode(str,encode);
	    	} catch (UnsupportedEncodingException e) {
	    			e.printStackTrace();
	    	}catch(Exception e){
	    		    e.printStackTrace();
	    	}
	    	return s;
    }
	 /*
	     * UTF-8页面转码
	     */
	 public static String encode(String str){
		    String s = null;
	    	try {
	    		s = java.net.URLEncoder.encode(str,"UTF-8");
	    	} catch (UnsupportedEncodingException e) {
	    			e.printStackTrace();
	    	}catch(Exception e){
	    		    e.printStackTrace();
	    	}
	    	return s;
 }
	  
	public static void main(String args[]){
		String str ="123456";
		System.out.println(str + " md5 is :" + EncodeUtil.MD5_32(str));
	}
}
